from flask import request
from models.product import Product
from models.store import Store
from extensions import db
from utils.auth import token_required
from flask_restx import Namespace, Resource, fields
import uuid

api = Namespace('products', description='商品管理相关接口')

# 定义API模型
product_model = api.model('Product', {
    'product_id': fields.String(required=True, description='商品ID'),
    'name': fields.String(required=True, description='商品名称'),
    'price': fields.Float(required=True, description='商品价格'),
    'description': fields.String(description='商品描述'),
    'is_deleted': fields.Boolean(description='是否删除'),
    'image_url': fields.String(description='商品图片URL'),
    'commission_rate': fields.Float(description='提成比例', default=0.0),
    'charge_type': fields.Integer(description='扣费类型：1-固定金额 2-比例', default=1),
    'charge_value': fields.Float(description='扣费值（根据charge_type决定是固定金额还是比例）', default=0.0)
})

base_response = api.model('BaseResponse', {
    'status': fields.String(description='响应状态'),
    'message': fields.String(description='响应消息')
})

product_response = api.inherit('ProductResponse', base_response, {
    'data': fields.Nested(product_model)
})

product_list_response = api.inherit('ProductListResponse', base_response, {
    'data': fields.Nested(api.model('PaginationData', {
        'list': fields.List(fields.Nested(product_model)),
        'total': fields.Integer(description='总记录数'),
        'pages': fields.Integer(description='总页数')
    }))
})

@api.route('', strict_slashes=False)
class ProductList(Resource):
    @api.doc('获取所有商品列表', params={
        'name': {'description': '商品名称模糊查询', 'required': False},
        'is_deleted': {'description': '是否删除', 'required': False, 'type': 'boolean'},
        'store_id': {'description': '店铺ID', 'required': False},
        'page': {'description': '页码', 'required': False, 'type': 'int'},
        'limit': {'description': '每页数量', 'required': False, 'type': 'int'}
    })
    @api.marshal_with(product_list_response)
    @token_required
    def get(self):
        """获取所有商品列表"""
        name = request.args.get('name')
        store_id = request.args.get('store_id')
        page = request.args.get('page', type=int)
        limit = request.args.get('limit', type=int)
        is_deleted = request.args.get('is_deleted', type=lambda x: x.lower() == 'true' if x else None)
        
        query = Product.query
        
        if is_deleted is not None:
            query = query.filter_by(is_deleted=is_deleted)
        
        if name:
            query = query.filter(Product.name.like(f'%{name}%'))
        if store_id:
            query = query.filter_by(store_id=store_id)
            
        query = query.order_by(db.desc(Product.id))
        
        # 分页处理
        if page and limit:
            pagination = query.paginate(page=page, per_page=limit, error_out=False)
            products = pagination.items
            return {
                'status': 'success',
                'message': '获取成功',
                'data': {
                    'list':[product.to_dict() for product in products],
                    'total': pagination.total,
                    'pages': pagination.pages
                },
                
            }, 200
        else:
            products = query.all()
            return {
                'status': 'success',
                'message': '获取成功',
                'data': {
                    'list':[product.to_dict() for product in products],
                    'total': 0,
                    'pages': 0
                },
            }, 200

  

    @api.doc('创建新商品')
    @api.expect(product_model)
    @api.marshal_with(product_response)
    @token_required
    def post(self):
        """创建新商品"""
        data = request.get_json()
        
        # 检查必填字段
        required_fields = ['name', 'price']
        for field in required_fields:
            if field not in data:
                return {
                    'status': 'error',
                    'message': f'缺少必填字段: {field}',
                    'data': None
                }, 400

        # 创建新商品
        new_product = Product(
            name=data['name'],
            price=data['price'],
            description=data.get('description'),
            image_url=data.get('image_url'),
            commission_rate=data.get('commission_rate', 0.0),
            charge_type=data.get('charge_type', 1),
            charge_value=data.get('charge_value', 0.0)
        )
        
        db.session.add(new_product)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '商品创建成功',
            'data': new_product.to_dict()
        }, 201

@api.route('/<product_id>')
class ProductResource(Resource):
    @api.doc('获取单个商品信息')
    @api.marshal_with(product_response)
    @token_required
    def get(self, product_id):
        """获取单个商品信息"""
        product = Product.query.filter_by(product_id=product_id).first()
        if not product:
            return {
                'status': 'error',
                'message': '商品不存在'
            }, 404
        
        return {
            'status': 'success',
            'data': product.to_dict()
        }, 200

    @api.doc('更新商品信息')
    @api.expect(product_model)
    @api.marshal_with(product_response)
    @token_required
    def put(self, product_id):
        """更新商品信息"""
        product = Product.query.filter_by(product_id=product_id).first()
        if not product:
            return {
                'status': 'error',
                'message': '商品不存在'
            }, 404
        
        data = request.get_json()
        
        # 更新商品信息
        if 'name' in data:
            product.name = data['name']
        if 'price' in data:
            product.price = data['price']
        if 'description' in data:
            product.description = data['description']
        if 'image_url' in data:
            product.image_url = data['image_url']
        if 'is_deleted' in data:
            product.is_deleted = data['is_deleted']
        if 'commission_rate' in data:
            product.commission_rate = data['commission_rate']
        if 'charge_type' in data:
            product.charge_type = data['charge_type']
        if 'charge_value' in data:
            product.charge_value = data['charge_value']
        
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '商品信息更新成功',
            'data': product.to_dict()
        }, 200
